import Vue from 'vue'
import VueRouter from 'vue-router'
import {origindyroutes} from "@/router/index1"
import service from "@/utils/request";
import HomeView from "@/views/HomeView.vue";

Vue.use(VueRouter)
export {dyroutes, dyroutesGroup}
//注意：dyroutes结构如下：
/*
[

    [    // dyroutes[0] , 路由分组0
        { path: '/xx', name: 'home', component: HomeView, children: [ ] } ,
        { path: '/yy', name: 'home', component: HomeView, children: [ ] }
    ]
    [   // dyroutes[1] ，路由分组1
        { path: '/aa', name: 'home', component: HomeView, children: [ ] } ,
        { path: '/bb', name: 'home', component: HomeView, children: [ ] }
    ]
]
 */
/*dyroutesGroup的结构如下：

[
    {id: 4, name: "设备管理", routepath: "/ycgl/yckz", rootmenuids: null, menuTreeList: 指向dyroutes[0]
    ,
    {id: 4, name: "系统管理", routepath: "/sys/user", rootmenuids: null, menuTreeList: 指向dyroutes[1]
]
 */

var dyroutes = []  //这个数组最终会包含所有的路由，并在其内部按照分组存放。
var dyroutesGroup = []  //这个数组包含上面的所有的路由分组，将上面的dyroutes内的每个分组按照对象形式再起内部存放。

//注意，这里的第二个参数传入的是dyroutes[i],而不是dyroutes。
function restoreDyroutes(parentpath, menuTreeList, dyroutes) {
    for (var i = 0; i < menuTreeList.length; i++) {
        var obj = {...menuTreeList[i]}
        if (obj.meta) {
            obj.meta = JSON.parse(obj.meta)

            // console.log(obj.meta)
        } else
            obj.meta = {}
        // obj.meta = {}
        // obj.meta.affix = true
        if (parentpath == '')
            obj.meta.apiActiveMenu = obj.path
        else
            obj.meta.apiActiveMenu = parentpath + '/' + obj.path
        let pagefile = obj.pagefile
        //注意，这里不能直接写成 import('../views/' + obj.pagefile)，
        // 否则会报错vue-router.esm.js:16 [vue-router] Failed to resolve async component default: TypeError: Cannot read properties of undefined (reading 'pagefile')
        // obj.component = () => import('../views/' + obj.pagefile)
        obj.component = () => import('../views/' + pagefile)
        dyroutes[i] = obj;
        if (menuTreeList[i].children != null &&
            menuTreeList[i].children.length > 0) {
            dyroutes[i].children = []
            restoreDyroutes(obj.meta.apiActiveMenu, menuTreeList[i].children, dyroutes[i].children)
        }
    }
}

export function resetRoutes(allmenus) {
    // dyroutes = []
    while(dyroutes.length>0){
        dyroutes.pop()
    }
    while(dyroutesGroup.length>0){
        dyroutesGroup.pop()
    }
    let user = null
    if ((user = sessionStorage.getItem('user')) != null) {
        user = JSON.parse(user)
        for (let i = 0; i < user.menuTreeGroupList.length; i++) {
            dyroutes[i] = []
            restoreDyroutes('', user.menuTreeGroupList[i].menuTreeList, dyroutes[i])//注意，这里传入的是dyroutes[i]
            dyroutesGroup[i] = {...user.menuTreeGroupList[i]}
            dyroutesGroup[i].menuTreeList = dyroutes[i]
        }
        resetRouter()
        for (let i = 0; i < dyroutesGroup.length; i++) {
            router.addRoutes(dyroutesGroup[i].menuTreeList)
        }
        // router.addRoute({path: '*', redirect: '/404', hidden: true})
        // restoreDyroutes(user.menuTreeGroupList, dyroutes)
        // resetRouter()
        // router.addRoutes(dyroutes)
        // router.addRoute({path: '*', redirect: '/404', hidden: true})
    }
}


const createRouter = () => new VueRouter({
    routes: [
        {
            path: '/404',
            component: () => import('@/views/error-page/404'),
            hidden: true
        },
        {
            path: '/401',
            component: () => import('@/views/error-page/401'),
            hidden: true
        },
        {
            path: '/error',
            component: HomeView,
            redirect: 'noRedirect',
            name: 'ErrorPages',
            meta: {
                title: 'Error Pages',
                icon: '404'
            },
            children: [
                {
                    path: '401',
                    component: () => import('@/views/error-page/401'),
                    name: 'Page401',
                    meta: {title: '401', noCache: true}
                },
                {
                    path: '404',
                    component: () => import('@/views/error-page/404'),
                    name: 'Page404',
                    meta: {title: '404', noCache: true}
                }
            ]
        },
        {path: '/login', name: '登录', component: () => import('../views/Login.vue')},
        {path: '/about', name: '关于', component: () => import('../views/AboutView.vue')},
    ]
})

const router = createRouter()

//江路由恢复至只有login
export function resetRouter() {
    const newRouter = createRouter()
    router.matcher = newRouter.matcher // reset router
}

router.beforeEach((to, from, next) => {
    if (to.path != '/login') {
        if (!sessionStorage.getItem('user')) {
            next('/login')
        } else {
            next()
        }
    } else {
        next()
    }
})

resetRoutes()


//这段代码是网上拷贝的，去掉就会出现错误：NavigationDuplicated：Avoided redundant navigation to current location
// 从网上百度的解决方法：vue项目NavigationDuplicated：Avoided redundant navigation to current location（重复请求相同路径警告）解决办法
//从代码看似乎只是用catch隐藏了错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

export default router
